package api;


import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

public class ZKget {

    String ip = "azyjz.ltd:2181";
    private ZooKeeper zooKeeper;

    @Before
    public void before() throws Exception{
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        zooKeeper= new ZooKeeper(ip, 50000, new Watcher() {
            public void process(WatchedEvent event) {
                System.out.println("创建连接成功");
                countDownLatch.countDown();
            }
        });
        countDownLatch.await();
    }

    @Test
    public void get1() throws  Exception{
        // 同步获取节点
        //arg1: 节点路径
        //arg2: watch 监视器，传false表示不使用监视器，true为使用默认监视器；可传自定义监视器
       /** arg3: 节点状态信息  {@link ZooKeeper#getData(java.lang.String, org.apache.zookeeper.Watcher, org.apache.zookeeper.data.Stat)}*/
        Stat stat=new Stat();
        byte[] data = zooKeeper.getData("/get/node1", false, stat);
        System.out.println(new String(data));
        System.out.println(stat.getVersion());


    }

    @Test
    public void get2() throws  Exception{
        // 同步获取节点
        // arg1:节点路径
        // arg2:watcher
        // arg3:回调接口
        Stat stat=new Stat();
       zooKeeper.getData("/get/node1", false,new AsyncCallback.DataCallback() {
           public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
               // 0代表读取成功
               System.out.println(rc);
                // 节点的路径
               System.out.println(path);
                // 上下文参数对象
               System.out.println(ctx);
                // 数据
               System.out.println(new String(data));
                // 属性对象
               System.out.println(stat.getVersion());
           }
       },"im context");
        Thread.sleep(10000);
        System.out.println("结束");

    }

    @After
    public void after() throws InterruptedException {
        zooKeeper.close();
    }
}
